<template>
  <div class="articleList">
    <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        success-duration="1500"
        @load="onLoad"
      >
        <article-item
          v-for="(item, index) in list"
          :key="index"
          :article-item="item"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article'
import articleItem from '@/components/articleItem.vue'
export default {
  name: 'ArticleList',
  components: {
    articleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      pre_timestamp: null,
      error: false,
      refreshing: false
    }
  },
  methods: {
    async onLoad() {
      try {
        // 异步更新数据
        const {
          data: { data }
        } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.pre_timestamp || Date.now(),
          with_top: 1
        })
        this.pre_timestamp = data.pre_timestamp
        this.list.push(...data.results)
        // 加载状态结束
        this.loading = false
        if (data.results.length === 0) {
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        this.error = true
      }
    },
    async onRefresh() {
      try {
        // 异步更新数据
        const {
          data: { data }
        } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        this.pre_timestamp = data.pre_timestamp
        this.list.unshift(...data.results)
        this.refreshing = false
      } catch (error) {
        this.isRefreshLoading = false // 关闭下拉刷新的 loading 状态
        this.$toast('刷新失败')
      }
    }
  }
}
</script>

<style scope lang="less">
.articleList {
    height: 79vh;
    overflow-y: auto;
}
</style>
